package com.dbapp.garden.controller.teaching;

import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.entity.GardenReceiptTemplate;
import com.dbapp.garden.service.GardenReceiptTemplateService;
import com.dbapp.garden.vm.ReceiptTemplateVm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author by gangzi on 2017/11/13.
 *         打印小票模版 控制器类
 */
@Controller
public class GardenReceiptTemplateController {

    @Autowired
    private GardenReceiptTemplateService templateService;

    @GetMapping("/receipttemplate")
    @ResponseBody
    public Map<String, ?> getReceiptTemplate(HttpServletRequest request, Integer type) {

        type = type == null ? 1 : type;
        Map<String, Object> map = new HashMap<>(16);
        map.put("type",type);
        List<GardenReceiptTemplate> courseRuleList = templateService.getReceiptTemplate(map);
        if (courseRuleList != null && !courseRuleList.isEmpty()) {
            return RenderJSON.makeStandMap(1, "恭喜您，获取成功", courseRuleList.get(0));
        } else {
            String message="对不起，暂无预约排课模版，请编辑！";
            if (type==2){
                message="对不起，暂无按次刷卡模版，请编辑！";
            }
            return RenderJSON.makeStandMap(1, message, "error");
        }

    }

    @PutMapping("/receipttemplate/{id}")
    @ResponseBody
    public Map<String, ?> editReceiptTemplate(@PathVariable("id") Integer id,@RequestBody @Valid ReceiptTemplateVm templateVm) {
        GardenReceiptTemplate template;
        if (id==0){
            template = new GardenReceiptTemplate();
            template.setContent(templateVm.getContent());
            template.setType(templateVm.getType());
            template.setCreateTime(new Date());
            template.setUpdateTime(new Date());
        }else{
            template = templateService.findById(id);
            template.setContent(templateVm.getContent());
            template.setType(templateVm.getType());
            template.setId(id);
            template.setUpdateTime(new Date());
        }


        Integer result = templateService.save(template);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }
    }

}
